package com.example.show_auto.ui.pages

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.PopupProperties
import androidx.compose.ui.platform.LocalContext
import com.example.show_auto.data.Guest
import com.example.show_auto.viewmodel.MainViewModel
import com.example.show_auto.ui.utils.DeviceCompatibility
import com.example.show_auto.ui.utils.OppoCompatibilityFix
import com.example.show_auto.data.SettingsStorage
import com.example.show_auto.data.Recipe
import androidx.compose.ui.text.style.TextOverflow

/**
 * 查询碰瓷贵客页面
 * 用于查询贵客信息和相关菜谱
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GuestQueryPage(
    viewModel: MainViewModel,
    onMenuClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    val gameData by viewModel.gameData.collectAsState()
    val uiState by viewModel.uiState.collectAsState()
    val filteredRecipes by viewModel.filteredRecipes.collectAsState()
    val context = LocalContext.current
    val settingsStorage = remember { SettingsStorage(context) }
    
    var searchQuery by remember { mutableStateOf("") }
    var selectedGuest by remember { mutableStateOf<Guest?>(null) }
    var isDropdownExpanded by remember { mutableStateOf(false) }
    val interactionSource = remember { MutableInteractionSource() }
    
    // 使用说明弹窗状态
    var showUsageDialog by remember { mutableStateOf(false) }
    
    // Tab切换状态
    var selectedTabIndex by remember { mutableStateOf(0) } // 0: 查询贵客碰瓷, 1: 查询神级符文碰瓷
    
    // 符文查询相关状态
    var runeSearchQuery by remember { mutableStateOf("") }
    var selectedRunes by remember { mutableStateOf<Set<String>>(emptySet()) }
    var isRuneDropdownExpanded by remember { mutableStateOf(false) }
    var hasQueriedRuneResults by remember { mutableStateOf(false) }
    val runeInteractionSource = remember { MutableInteractionSource() }
    
    // 符文分类筛选状态 - 神级符文碰瓷页面单独存储
    var showGoldRunesForGodRune by remember { mutableStateOf<Boolean>(settingsStorage.getShowGoldRunesForGodRune()) }
    var showSilverRunesForGodRune by remember { mutableStateOf<Boolean>(settingsStorage.getShowSilverRunesForGodRune()) }
    var showBronzeRunesForGodRune by remember { mutableStateOf<Boolean>(settingsStorage.getShowBronzeRunesForGodRune()) }
    
    // 符文分类定义
    val goldRunes = remember {
        listOf("恐怖利刃", "鼓风机", "蒸馏杯", "千年煮鳖", "香烤鱼排", "五星炒果")
    }
    val silverRunes = remember {
        listOf("刀嘴鹦鹉", "一昧真火", "蒸汽宝石", "耐煮的水草", "焦虫", "暖石")
    }
    val bronzeRunes = remember {
        listOf("剪刀蟹", "油火虫", "蒸汽耳环", "防水的柠檬", "烤焦的菊花", "五香果")
    }
    
    // 全部符文列表
    val allRunes = remember {
        goldRunes + silverRunes + bronzeRunes
    }

    // 根据分类筛选和搜索条件过滤符文
    val filteredRunes = remember(runeSearchQuery, selectedRunes, showGoldRunesForGodRune, showSilverRunesForGodRune, showBronzeRunesForGodRune, gameData) {
        // 根据分类筛选确定可用符文
        val availableRunes = when {
            showGoldRunesForGodRune -> goldRunes
            showSilverRunesForGodRune -> silverRunes
            showBronzeRunesForGodRune -> bronzeRunes
            else -> allRunes // 没有分类选择时显示所有符文
        }
        
        // 再根据搜索条件过滤
        availableRunes.filter { rune ->
            if (runeSearchQuery.isEmpty()) {
                true // 空搜索时显示所有符文
            } else {
                // 支持符文名称搜索
                val matchesRuneName = rune.contains(runeSearchQuery, ignoreCase = true)
                
                // 支持菜谱名称搜索：查找gift字段为该符文的菜谱，然后检查菜谱名称是否匹配搜索词
                val matchesRecipeName = gameData?.recipes?.any { recipe ->
                    recipe.gift == rune && recipe.gift != "-" && 
                    recipe.name.contains(runeSearchQuery, ignoreCase = true)
                } ?: false
                
                matchesRuneName || matchesRecipeName
            }
        }
    }

    // 监听输入框点击事件
    LaunchedEffect(interactionSource) {
        interactionSource.interactions.collect { interaction ->
            when (interaction) {
                is PressInteraction.Press -> {
                    if (selectedGuest == null) {
                        isDropdownExpanded = true
                    }
                }
            }
        }
    }
    
    // 计算贵客剩余可碰瓷次数的函数
    fun calculateRemainingGuestCount(guest: Guest): Int {
        val allRecipes = gameData?.recipes ?: return 0
        var totalRemaining = 0
        
        // 遍历已拥有的菜谱，找到包含该贵客的菜谱
        allRecipes.filter { recipe -> 
            recipe.got && // 只统计已拥有的菜谱
            recipe.guests.any { it.guest == guest.name }
        }.forEach { recipe ->
            // 计算该菜谱中该贵客的剩余碰瓷次数
            // 按照 RankGuestColumn 显示逻辑：只看前3个位置（优、特、神）
            recipe.guests.take(3).forEachIndexed { index, recipeGuest ->
                if (recipeGuest.guest == guest.name) {
                    // 按照 RankGuestColumn 的逻辑：
                    // index=0 对应优级升阶贵客，targetRank=2
                    // index=1 对应特级升阶贵客，targetRank=3
                    // index=2 对应神级升阶贵客，targetRank=4
                    val targetRank = index + 2
                    val isCompleted = recipe.rank >= targetRank
                    
                    // 每个未完成的位置都单独计算一次碰瓷机会
                    if (!isCompleted) {
                        totalRemaining++
                    }
                }
            }
        }
        
        return totalRemaining
    }
    
    // 根据搜索条件过滤贵客（简单直接，无防抖）
    val filteredGuests = remember(gameData, searchQuery, selectedGuest) {
        if (selectedGuest != null) {
            emptyList() // 如果已选择贵客，不显示列表
        } else {
            val guests = gameData?.guests?.filter { guest ->
                if (searchQuery.isEmpty()) {
                    true // 空搜索时显示所有贵客
                } else {
                    guest.name.contains(searchQuery, ignoreCase = true)
                }
            } ?: emptyList()
            
            // 按碰瓷次数排序
            guests.sortedWith { guest1, guest2 ->
                val count1 = calculateRemainingGuestCount(guest1)
                val count2 = calculateRemainingGuestCount(guest2)
                
                // 优先显示有碰瓷次数的贵客
                when {
                    count1 > 0 && count2 == 0 -> -1 // guest1 有次数，guest2 没有，guest1 在前
                    count1 == 0 && count2 > 0 -> 1  // guest1 没有，guest2 有次数，guest2 在前
                    count1 > 0 && count2 > 0 -> count2.compareTo(count1) // 都有次数，次数多的在前
                    else -> guest1.name.compareTo(guest2.name) // 都没有次数或都有次数但相等，按名称排序
                }
            }
        }
    }

    // 当选择贵客时，自动查询菜谱
    LaunchedEffect(selectedGuest) {
        selectedGuest?.let { guest ->
            viewModel.selectGuest(guest)
        }
    }

    
    OppoCompatibilityFix.FixedLayoutContainer(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部应用栏
        TopAppBar(
            title = { 
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                Text(
                        text = "查询碰瓷",
                    fontWeight = FontWeight.Medium
                )
                    Spacer(modifier = Modifier.width(8.dp))
                    IconButton(
                        onClick = { showUsageDialog = true },
                        modifier = Modifier.size(24.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Info,
                            contentDescription = "使用说明",
                            modifier = Modifier.size(20.dp)
                        )
                    }
                }
            },
            navigationIcon = {
                IconButton(onClick = onMenuClick) {
                    Icon(
                        imageVector = Icons.Default.Menu,
                        contentDescription = "菜单"
                    )
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )
        
        // 页面内容
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(OppoCompatibilityFix.getFixedSpacing(16.dp))
        ) {
            // Tab切换框
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp),
                shape = RoundedCornerShape(20.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color(0xFFE3F2FD)
                ),
                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
            ) {
                Row(
                    modifier = Modifier.padding(4.dp)
                ) {
                    // 查询贵客碰瓷标签
                    Surface(
                        onClick = { selectedTabIndex = 0 },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(16.dp),
                        color = if (selectedTabIndex == 0) {
                            MaterialTheme.colorScheme.primary
                        } else {
                            Color.Transparent
                        }
                    ) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "查询贵客碰瓷",
                                fontSize = 12.sp,
                                fontWeight = FontWeight.Medium,
                                color = if (selectedTabIndex == 0) {
                                    Color.White
                                } else {
                                    MaterialTheme.colorScheme.primary
                                }
                            )
                        }
                    }
                    
                    Spacer(modifier = Modifier.width(4.dp))
                    
                    // 查询神级符文碰瓷标签
                    Surface(
                        onClick = { selectedTabIndex = 1 },
                        modifier = Modifier
                            .weight(1f)
                            .height(28.dp),
                        shape = RoundedCornerShape(16.dp),
                        color = if (selectedTabIndex == 1) {
                            MaterialTheme.colorScheme.primary
                        } else {
                            Color.Transparent
                        }
                    ) {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "查询神级符文碰瓷",
                                fontSize = 12.sp,
                                fontWeight = FontWeight.Medium,
                                color = if (selectedTabIndex == 1) {
                                    Color.White
                                } else {
                                    MaterialTheme.colorScheme.primary
                                }
                            )
                        }
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 根据选择的tab显示不同内容
            when (selectedTabIndex) {
                0 -> {
                    // 查询贵客碰瓷页面
            // 贵客选择输入框（原生实现，不使用ExposedDropdownMenuBox）
            Box(modifier = Modifier.fillMaxWidth()) {
                OutlinedTextField(
                    value = selectedGuest?.name ?: searchQuery,
                    onValueChange = { query ->
                        searchQuery = query
                        selectedGuest = null
                        isDropdownExpanded = true // 输入时始终展开下拉列表
                    },
                    label = { Text("选择贵客") },
                    placeholder = { Text("输入贵客名称搜索") },
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Person,
                            contentDescription = "贵客"
                        )
                    },
                    trailingIcon = {
                        Row {
                            // 清除按钮
                            if (selectedGuest != null || searchQuery.isNotEmpty()) {
                                IconButton(
                                    onClick = {
                                        selectedGuest = null
                                        searchQuery = ""
                                        isDropdownExpanded = false
                                        viewModel.clearSelection()
                                    }
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Clear,
                                        contentDescription = "清除"
                                    )
                                }
                            }
                            
                            // 展开/收起按钮
                            IconButton(
                                onClick = {
                                    if (selectedGuest == null) {
                                        isDropdownExpanded = !isDropdownExpanded
                                    }
                                }
                            ) {
                                Icon(
                                    imageVector = if (isDropdownExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                    contentDescription = if (isDropdownExpanded) "收起" else "展开"
                                )
                            }
                        }
                    },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    colors = OppoCompatibilityFix.getFixedTextFieldColors(),
                    interactionSource = interactionSource
                )

                // 自定义下拉列表
                if (isDropdownExpanded && selectedGuest == null) {
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .offset(y = 80.dp) // 增加偏移量避免重叠
                            .heightIn(max = OppoCompatibilityFix.getFixedCardHeight(400.dp)),
                        elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
                        colors = OppoCompatibilityFix.getFixedCardColors()
                    ) {
                        if (filteredGuests.isNotEmpty()) {
                            LazyColumn {
                                items(filteredGuests) { guest ->
                                    Row(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .clickable {
                                                selectedGuest = guest
                                                searchQuery = ""
                                                isDropdownExpanded = false
                                                viewModel.selectGuest(guest)
                                            }
                                            .padding(horizontal = 12.dp, vertical = 12.dp),
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                        // 贵客名称 - 占60%宽度
                                        Text(
                                            text = guest.name,
                                            fontSize = 14.sp,
                                            color = MaterialTheme.colorScheme.onSurface,
                                            fontWeight = FontWeight.Medium,
                                            modifier = Modifier.weight(0.6f)
                                        )
                                        
                                        // 剩余可碰瓷次数 - 占40%宽度，左对齐
                                        val remainingCount = calculateRemainingGuestCount(guest)
                                        if (remainingCount > 0) {
                                            Text(
                                                text = "还可碰瓷 $remainingCount 次",
                                                fontSize = 12.sp,
                                                color = MaterialTheme.colorScheme.primary,
                                                fontWeight = FontWeight.Medium,
                                                textAlign = TextAlign.Start,
                                                modifier = Modifier.weight(0.4f)
                                            )
                                        } else {
                                            Text(
                                                text = "无可碰瓷菜谱",
                                                fontSize = 12.sp,
                                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                textAlign = TextAlign.Start,
                                                modifier = Modifier.weight(0.4f)
                        )
                    }
                                    }
                                    if (guest != filteredGuests.last()) {
                                        HorizontalDivider()
                                    }
                                }
                            }
                        } else {
                            Text(
                                text = "未找到匹配的贵客",
                                modifier = Modifier.padding(16.dp),
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))

            // 菜谱显示区域
            if (selectedGuest != null) {
                Card(
                    modifier = Modifier.fillMaxSize()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = if (selectedGuest != null) {
                                "${selectedGuest!!.name} 的菜谱 (${filteredRecipes.size})"
                            } else {
                                "请选择贵客"
                            },
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Medium,
                            modifier = Modifier.padding(8.dp)
                        )
                        
                        if (selectedGuest != null) {
                            if (filteredRecipes.isEmpty()) {
                                Box(
                                    modifier = Modifier.fillMaxSize(),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Column(
                                        horizontalAlignment = Alignment.CenterHorizontally
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Info,
                                            contentDescription = "无数据",
                                            tint = MaterialTheme.colorScheme.onSurfaceVariant,
                                            modifier = Modifier.size(48.dp)
                                        )
                                        Spacer(modifier = Modifier.height(8.dp))
                                        Text(
                                            text = "暂无相关菜谱",
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                        Text(
                                            text = "请先导入个人数据",
                                            fontSize = 12.sp,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }
                            } else {
                                LazyColumn {
                                    items(filteredRecipes) { recipe ->
                                        RecipeItem(
                                            recipe = recipe,
                                            selectedGuest = selectedGuest
                                        )
                                    }
                                }
                            }
                        } else {
                            Box(
                                modifier = Modifier.fillMaxSize(),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Person,
                                        contentDescription = "选择贵客",
                                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                                        modifier = Modifier.size(48.dp)
                                    )
                                    Spacer(modifier = Modifier.height(8.dp))
                                    Text(
                                        text = "请从上方下拉框选择贵客",
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
                1 -> {
                    // 查询神级符文碰瓷页面
                    // 符文搜索框（单选模式）
                    Box(modifier = Modifier.fillMaxWidth()) {
                        // 监听输入框点击事件
                        LaunchedEffect(runeInteractionSource) {
                            runeInteractionSource.interactions.collect { interaction ->
                                when (interaction) {
                                    is PressInteraction.Press -> {
                                        isRuneDropdownExpanded = true
                                    }
                                }
                            }
                        }
                        OutlinedTextField(
                            value = if (selectedRunes.isNotEmpty()) {
                                selectedRunes.first()
                            } else {
                                runeSearchQuery
                            },
                            onValueChange = { value ->
                                if (selectedRunes.isEmpty()) {
                                    runeSearchQuery = value
                                }
                                isRuneDropdownExpanded = true
                            },
                            label = { Text("选择符文") },
                            placeholder = { Text("输入符文名称或菜谱名称搜索", fontSize = 12.sp) },
                            modifier = Modifier.fillMaxWidth(),
                            readOnly = selectedRunes.isNotEmpty(), // 选择符文后设为只读，确保点击能被捕获
                            leadingIcon = {
                                Icon(
                                    imageVector = Icons.Default.Search,
                                    contentDescription = "搜索"
                                )
                            },
                            trailingIcon = {
                                if (selectedRunes.isNotEmpty()) {
                                    IconButton(
                                        onClick = {
                                            selectedRunes = emptySet()
                                            runeSearchQuery = ""
                                            isRuneDropdownExpanded = false
                                            hasQueriedRuneResults = false
                                        }
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Clear,
                                            contentDescription = "清除"
                                        )
                                    }
                                } else {
                                    IconButton(
                                        onClick = {
                                            isRuneDropdownExpanded = !isRuneDropdownExpanded
                                        }
                                    ) {
                                        Icon(
                                            imageVector = if (isRuneDropdownExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                            contentDescription = if (isRuneDropdownExpanded) "收起" else "展开"
                                        )
                                    }
                                }
                            },
                            singleLine = true,
                            colors = OppoCompatibilityFix.getFixedTextFieldColors(),
                            interactionSource = runeInteractionSource
                        )
                    }

                    // 下拉列表区域 - 只在展开且未查询结果时显示
                    if (isRuneDropdownExpanded && !hasQueriedRuneResults) {
                        Spacer(modifier = Modifier.height(4.dp))
                        
                        // 符文分类筛选按钮行
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp),
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            // 金符文按钮
                            OutlinedButton(
                                onClick = {
                                    showGoldRunesForGodRune = !showGoldRunesForGodRune
                                    if (showGoldRunesForGodRune) {
                                        showSilverRunesForGodRune = false
                                        showBronzeRunesForGodRune = false
                                    }
                                    // 保存状态到设置（神级符文碰瓷单独存储）
                                    settingsStorage.saveGodRuneFilterStates(showGoldRunesForGodRune, showSilverRunesForGodRune, showBronzeRunesForGodRune)
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (showGoldRunesForGodRune) MaterialTheme.colorScheme.primary else Color.White,
                                    contentColor = if (showGoldRunesForGodRune) Color.White else Color.Black
                                ),
                                shape = RoundedCornerShape(6.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = "金符文",
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }

                            // 银符文按钮
                            OutlinedButton(
                                onClick = {
                                    showSilverRunesForGodRune = !showSilverRunesForGodRune
                                    if (showSilverRunesForGodRune) {
                                        showGoldRunesForGodRune = false
                                        showBronzeRunesForGodRune = false
                                    }
                                    // 保存状态到设置（神级符文碰瓷单独存储）
                                    settingsStorage.saveGodRuneFilterStates(showGoldRunesForGodRune, showSilverRunesForGodRune, showBronzeRunesForGodRune)
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (showSilverRunesForGodRune) MaterialTheme.colorScheme.primary else Color.White,
                                    contentColor = if (showSilverRunesForGodRune) Color.White else Color.Black
                                ),
                                shape = RoundedCornerShape(6.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = "银符文",
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }

                            // 铜符文按钮
                            OutlinedButton(
                                onClick = {
                                    showBronzeRunesForGodRune = !showBronzeRunesForGodRune
                                    if (showBronzeRunesForGodRune) {
                                        showGoldRunesForGodRune = false
                                        showSilverRunesForGodRune = false
                                    }
                                    // 保存状态到设置（神级符文碰瓷单独存储）
                                    settingsStorage.saveGodRuneFilterStates(showGoldRunesForGodRune, showSilverRunesForGodRune, showBronzeRunesForGodRune)
                                },
                                modifier = Modifier
                                    .weight(1f)
                                    .height(32.dp),
                                colors = ButtonDefaults.outlinedButtonColors(
                                    containerColor = if (showBronzeRunesForGodRune) MaterialTheme.colorScheme.primary else Color.White,
                                    contentColor = if (showBronzeRunesForGodRune) Color.White else Color.Black
                                ),
                                shape = RoundedCornerShape(6.dp),
                                border = BorderStroke(1.dp, Color.Black),
                                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                            ) {
                                Text(
                                    text = "铜符文",
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Medium
                                )
                            }
                        }
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        // 符文列表卡片
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(max = OppoCompatibilityFix.getFixedCardHeight(400.dp)),
                            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
                            colors = OppoCompatibilityFix.getFixedCardColors()
                        ) {
                            if (filteredRunes.isNotEmpty()) {
                                LazyColumn {
                                    items(filteredRunes) { rune ->
                                        Row(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .clickable {
                                                    try {
                                                        // 单选模式：直接选择符文并触发查询
                                                        selectedRunes = setOf(rune)
                                                        runeSearchQuery = ""
                                                        isRuneDropdownExpanded = false
                                                        hasQueriedRuneResults = true
                                                    } catch (e: Exception) {
                                                        // 忽略符文选择错误
                                                    }
                                                }
                                                .padding(horizontal = 12.dp, vertical = 12.dp),
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            // 符文名称和选中状态 - 占50%宽度
                                            Row(
                                                modifier = Modifier.weight(0.5f),
                                                verticalAlignment = Alignment.CenterVertically
                                            ) {
                                                Text(
                                                    text = rune,
                                                    fontSize = 14.sp,
                                                    color = if (rune in selectedRunes) {
                                                        MaterialTheme.colorScheme.primary
                                                    } else {
                                                        MaterialTheme.colorScheme.onSurface
                                                    },
                                                    fontWeight = if (rune in selectedRunes) {
                                                        FontWeight.Bold
                                                    } else {
                                                        FontWeight.Medium
                                                    },
                                                    modifier = Modifier.weight(1f)
                                                )
                                                if (rune in selectedRunes) {
                                                    Icon(
                                                        imageVector = Icons.Default.Check,
                                                        contentDescription = "已选择",
                                                        tint = MaterialTheme.colorScheme.primary,
                                                        modifier = Modifier.size(16.dp)
                                                    )
                                                }
                                            }
                                            
                                            // 碰瓷数量信息 - 占50%宽度，左对齐
                                            Text(
                                                text = "还可碰瓷${viewModel.getRuneRecipeCount(rune)}个",
                                                fontSize = 12.sp,
                                                color = MaterialTheme.colorScheme.primary,
                                                fontWeight = FontWeight.Medium,
                                                textAlign = TextAlign.Start,
                                                modifier = Modifier
                                                    .weight(0.5f)
                                                    .padding(start = 8.dp)
                                            )
                                        }
                                        if (rune != filteredRunes.last()) {
                                            HorizontalDivider()
                                        }
                                    }
                                }
                            } else {
                                Text(
                                    text = "未找到匹配的符文",
                                    modifier = Modifier.padding(16.dp),
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(16.dp))

                    // 查询结果显示区域 - 只在有查询结果时显示
                    if (hasQueriedRuneResults && selectedRunes.isNotEmpty()) {
                        // 触发查询
                        LaunchedEffect(selectedRunes.first()) {
                            viewModel.selectRune(selectedRunes.first())
                        }
                        
                        // 显示查询结果
                        Surface(
                            modifier = Modifier.fillMaxSize(),
                            color = Color(0xFFE8E8E8), // 灰色背景
                            shape = RoundedCornerShape(8.dp)
                        ) {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp)
                            ) {
                                // 菜谱列表
                                LazyColumn(
                                    verticalArrangement = Arrangement.spacedBy(8.dp)
                                ) {
                                    items(filteredRecipes) { recipe ->
                                        RuneRecipeItem(
                                            recipe = recipe,
                                            selectedRune = selectedRunes.first()
                                        )
                                    }
                                    
                                    if (filteredRecipes.isEmpty()) {
                                        item {
                                            Column(
                                                modifier = Modifier
                                                    .fillMaxWidth()
                                                    .padding(24.dp),
                                                horizontalAlignment = Alignment.CenterHorizontally
                                            ) {
                                                Icon(
                                                    imageVector = Icons.Default.Search,
                                                    contentDescription = "无结果",
                                                    tint = MaterialTheme.colorScheme.onSurfaceVariant,
                                                    modifier = Modifier.size(48.dp)
                                                )
                                                Spacer(modifier = Modifier.height(8.dp))
                                                Text(
                                                    text = "暂无符合条件的菜谱",
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                    fontSize = 16.sp,
                                                    fontWeight = FontWeight.Medium
                                                )
                                                Text(
                                                    text = "该符文暂无未达到神级的已拥有菜谱",
                                                    fontSize = 12.sp,
                                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                    textAlign = TextAlign.Center
                                                )
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 使用说明弹窗
    if (showUsageDialog) {
        GuestUsageGuideDialog(
            onDismiss = { showUsageDialog = false }
        )
    }
}

/**
 * 贵客项组件
 */
@Composable
private fun GuestItem(
    guest: Guest,
    isSelected: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    val backgroundColor = if (isSelected) {
        MaterialTheme.colorScheme.primaryContainer
    } else {
        MaterialTheme.colorScheme.surface
    }
    
    val contentColor = if (isSelected) {
        MaterialTheme.colorScheme.onPrimaryContainer
    } else {
        MaterialTheme.colorScheme.onSurface
    }

    Card(
        onClick = onClick,
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = 2.dp),
        colors = CardDefaults.cardColors(
            containerColor = backgroundColor
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 星级显示
            Text(
                                                text = "",
                fontSize = 14.sp,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.width(60.dp)
            )
            
            Spacer(modifier = Modifier.width(8.dp))
            
            // 贵客名称
            Text(
                text = guest.name,
                fontSize = 14.sp,
                color = contentColor,
                modifier = Modifier.weight(1f)
            )
        }
    }
}

/**
 * 菜谱项组件
 */
@Composable
private fun RecipeItem(
    recipe: com.example.show_auto.data.Recipe,
    selectedGuest: Guest?,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = 2.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 左侧：菜谱名称和星级
                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    // 第一行：菜谱名称
                    Text(
                        text = recipe.name,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Medium
                    )
                    
                    // 第二行：星级
                    Text(
                        text = recipe.getRarityStars(),
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.primary
                    )
                }

                // 右侧：升阶贵客（固定宽度）
                RankGuestColumn(
                    recipe = recipe,
                    selectedGuest = selectedGuest,
                    modifier = Modifier.width(100.dp)
                )
            }
        }
    }
}

/**
 * 升阶贵客列显示组件
 */
@Composable
private fun RankGuestColumn(
    recipe: com.example.show_auto.data.Recipe,
    selectedGuest: Guest?,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.Start
    ) {
        // 显示三个品阶的升阶贵客
        val rankLabels = listOf("优", "特", "神")

        recipe.guests.take(3).forEachIndexed { index, recipeGuest ->
            val rankLabel = rankLabels.getOrNull(index) ?: ""
            val targetRank = index + 2 // 优=2, 特=3, 神=4
            val isCompleted = recipe.rank >= targetRank
            val isCurrentGuest = selectedGuest?.name == recipeGuest.guest

            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.padding(vertical = 1.dp)
            ) {
                // 使用字符串拼接显示品阶和贵客名称
                        Text(
                    text = "$rankLabel-${recipeGuest.guest}",
                            fontSize = 12.sp,
                    color = when {
                        isCompleted -> MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                        isCurrentGuest -> MaterialTheme.colorScheme.primary
                        else -> MaterialTheme.colorScheme.onSurface
                    },
                    fontWeight = if (isCurrentGuest) FontWeight.Medium else FontWeight.Normal,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }

        // 如果升阶贵客不足3个，用空行填充
        repeat(3 - recipe.guests.size) {
            Spacer(modifier = Modifier.height(14.dp))
        }
    }
}

/**
 * 贵客查询使用说明弹窗组件
 */
@Composable
private fun GuestUsageGuideDialog(
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
                        Text(
                text = "碰瓷贵客查询使用说明",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            LazyColumn(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                item {
                    Text(
                        text = "什么是碰瓷？",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "      碰瓷指的是菜谱品级每次升阶时，会必定遇见指定贵客，可以通过碰瓷的方式来快速完成遇见指定贵客的任务以及厨师修炼任务等。\n      PS：获得新菜谱后不要着急做到最高品级，保留碰瓷可节省大量任务时间。",
                            fontSize = 14.sp,
                        lineHeight = 20.sp
                    )
                }

                item {
                    Text(
                        text = "什么是神级符文碰瓷？",
                        fontSize = 16.sp,
                            fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "      菜谱达到神级时会固定获得某个符文，可理由这个机制获得符文。\n      PS：不要直接把菜谱做到神级，会损失很多贵客碰瓷机会。",
                        fontSize = 14.sp,
                        lineHeight = 20.sp
                    )
                }
                
                item {
                    Text(
                        text = "如何使用？",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "1. 在搜索框中输入贵客名称/符文名称\n2. 从下拉列表中选择要查询的贵客/符文\n3. 查看该贵客/符文所有可碰瓷的菜谱\n4. 右侧显示每个菜谱的升阶贵客信息\n5. 灰色代表已碰瓷，蓝色代表可碰瓷，已碰瓷的贵客无法再次碰瓷",
                        fontSize = 14.sp,
                        lineHeight = 20.sp
                    )
                }
                
                item {
                    Text(
                        text = "菜谱碰瓷建议",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "• 碰瓷时菜谱只需要制作一份即可\n• 需要考虑贵客冲突，避免贵客冲突的菜谱同时碰瓷，建议每次只碰瓷一道菜\n• 神级符文碰瓷建议只在符文应急时使用，并且优先使用已经达到特级的菜谱",
                        fontSize = 14.sp,
                        lineHeight = 20.sp
                    )
                }
                
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("知道了")
                        }
                    }
    )
}

/**
 * 符文菜谱项组件
 */
@Composable
private fun RuneRecipeItem(
    recipe: Recipe,
    selectedRune: String,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = 2.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth()
            ) {
                // 左侧：菜谱名称和星级
                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    // 第一行：菜谱名称
                    Text(
                        text = recipe.name,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Medium
                    )
                    
                    // 第二行：星级
                    Text(
                        text = recipe.getRarityStars(),
                        fontSize = 12.sp,
                        color = MaterialTheme.colorScheme.primary
                    )
                }

                // 右侧：升阶贵客信息（固定宽度）
                RuneRankGuestColumn(
                    recipe = recipe,
                    modifier = Modifier.width(100.dp)
                )
            }
        }
    }
}

/**
 * 符文菜谱的升阶贵客列显示组件
 */
@Composable
private fun RuneRankGuestColumn(
    recipe: Recipe,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.Start
    ) {
        // 显示三个品阶的升阶贵客
        val rankLabels = listOf("优", "特", "神")

        recipe.guests.take(3).forEachIndexed { index, recipeGuest ->
            val rankLabel = rankLabels.getOrNull(index) ?: ""
            val targetRank = index + 2 // 优=2, 特=3, 神=4
            val isCompleted = recipe.rank >= targetRank

            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.padding(vertical = 1.dp)
            ) {
                // 使用字符串拼接显示品阶和贵客名称
                Text(
                    text = "$rankLabel-${recipeGuest.guest}",
                    fontSize = 12.sp,
                    color = if (isCompleted) {
                        MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                    } else {
                        MaterialTheme.colorScheme.onSurface
                    },
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }

        // 如果升阶贵客不足3个，用空行填充
        repeat(3 - recipe.guests.size) {
            Spacer(modifier = Modifier.height(14.dp))
        }
    }
}

/**
 * 获取品级标签
 */
private fun getRankLabel(rank: Int): String {
    return when (rank) {
        0 -> "未制作"
        1 -> "一品"
        2 -> "二品"
        3 -> "三品"
        4 -> "神级"
        else -> "未知"
    }
}
